/**
 * CollectionUtil.java
 */
package com.mht2017.common.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author yutong.xiao
 * @date 2017年5月11日 下午3:11:13
 */
public class CollectionUtil {

	public static Object getFirst(Object object) {
		if (null == object) {
			return null;
		}

		if (object instanceof Iterator<?>) {
			return ((Iterator<?>) object).hasNext() ? ((Iterator<?>) object).next() : null;
		} else if (object instanceof Iterable<?>) {
			return getFirst(((Iterable<?>) object).iterator());
		} else {
			return null;
		}
	}

	public static <T> T getFirst(Iterable<T> iterable) {
		if (null == iterable) {
			return null;
		}

		return getFirst(iterable.iterator());
	}

	public static <T> T getFirst(Iterator<T> iterator) {
		if (null == iterator) {
			return null;
		}

		return iterator.hasNext() ? iterator.next() : null;
	}

	public static <T> List<T> getBefore(Iterable<T> iterable, int count) {
		if (null == iterable) {
			return null;
		}

		return getBefore(iterable.iterator(), count);
	}

	public static <T> List<T> getBefore(Iterator<T> iterator, int count) {
		if (null == iterator) {
			return null;
		}
		if (count < 0) {
			throw new RuntimeException(String.format("count(%s)不应该小于0", count));
		}

		List<T> results = new ArrayList<>(count);
		for (int i = 0; i < count && iterator.hasNext(); i++) {
			results.add(iterator.next());
		}

		return results;
	}

	public static Object get(Object object, int index) {
		if (null == object || index < 0) {
			return null;
		}

		if (object instanceof List<?>) {
			List<?> list = (List<?>) object;
			return list.isEmpty() ? null : list.get(Math.min(list.size() - 1, index));
		}

		return null;
	}

	public static <T> T getLast(List<T> list) {
		if (null == list) {
			return null;
		}

		return list.isEmpty() ? null : list.get(list.size() - 1);
	}

}
